<template>
  <view class="uni-container">
    <uni-forms
      ref="form"
      :model="formData"
      validateTrigger="bind"
      label-width="120px"
    >
      <uni-forms-item
        name="user_id"
        label="活动发起者ID"
        required
        v-if="isSuperAdmin"
      >
        <uni-easyinput
          placeholder="活动发起者的ID， 参考`uni-id-users` 表"
          :disabled="true"
          v-model="formData.user_id"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- 原有表单项添加 :disabled 属性 -->
      <uni-forms-item name="category_id" label="分类" required>
        <uni-data-picker
          v-model="formData.category_id"
          collection="opendb-news-categories"
          field="name as text, _id as value"
          :disabled="isDisabled"
        ></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="title" label="活动名称" required>
        <uni-easyinput
          placeholder="活动的标题名称"
          v-model="formData.title"
          trim="both"
          :disabled="isDisabled"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="avatar" label="封面大图" required>
        <uni-file-picker
          v-model="formData.avatar"
          fileMediatype="image"
          :auto-upload="true"
          return-type="object"
          :disabled="isDisabled"
        ></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="content" label="活动详情大图" required>
        <uni-file-picker
          v-model="formData.content"
          fileMediatype="image"
          :auto-upload="true"
          return-type="object"
        ></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="article_status" label="活动状态">
        <uni-data-checkbox
          v-model="formData.article_status"
          :localdata="formOptions.article_status_localdata"
        ></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="start_time" label="开始时间" required>
        <uni-datetime-picker
          return-type="timestamp"
          v-model="formData.start_time"
        ></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="end_time" label="结束时间" required>
        <uni-datetime-picker
          return-type="timestamp"
          v-model="formData.end_time"
        ></uni-datetime-picker>
      </uni-forms-item>

      <!-- 新增地区选择器 -->
      <w-three-picker
        ref="pickerRegionAddress"
        :title="['省', '市', '区']"
        :localdata="provinces"
        v-model="valueAddress"
        @confirm="confirmRegionAddress"
        :is-mask-click="false"
        :show-cancel="true"
        text-field="name"
        value-field="code"
      />
      <uni-forms-item name="region_address" label="活动的省/市/区" required>
        <button
          v-if="!hasRegionAddressTest"
          @click="handleShowRegionAddress"
          class="uni-button"
          size="mini"
          type="primary"
        >
          添加
        </button>
        <uni-easyinput
          v-else
          @click="handleShowRegionAddress"
          placeholder="省/市/区"
          v-model="regionAddressText"
          trim="both"
          disabled
        />
        <button
          v-if="hasRegionAddressTest"
          @click="handleShowRegionAddress"
          style="margin-top: 10px"
          class="uni-button"
          size="mini"
          type="primary"
        >
          修改
        </button>
        <button
          v-if="hasRegionAddressTest"
          @click="handleDeleteRegionAddress"
          style="margin-left: 5px; margin-top: 10px"
          class="uni-button"
          size="mini"
          type="warn"
        >
          删除
        </button>
      </uni-forms-item>

      <uni-forms-item name="location_name" label="活动地点名称" required>
        <uni-easyinput
          placeholder="活动举办地点名称"
          v-model="formData.location_name"
          trim="both"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- <uni-forms-item name="last_comment_user_id" label="">
        <uni-easyinput placeholder="最后回复用户 id，参考`uni-id-users` 表"
          v-model="formData.last_comment_user_id"></uni-easyinput>
      </uni-forms-item> -->
      <uni-forms-item name="publish_date" label="发表时间">
        <uni-datetime-picker
          return-type="timestamp"
          v-model="formData.publish_date"
        ></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="last_modify_date" label="最后修改时间">
        <uni-datetime-picker
          return-type="timestamp"
          v-model="formData.last_modify_date"
        ></uni-datetime-picker>
      </uni-forms-item>
      <!-- <uni-forms-item name="coupon_id" label="">
        <uni-easyinput placeholder="关联的优惠卷id, 参考`coupons`表" v-model="formData.coupon_id"></uni-easyinput>
      </uni-forms-item> -->
      <uni-forms-item name="view_count" label="阅读数量">
        <uni-easyinput
          placeholder="阅读数量"
          type="number"
          v-model="formData.view_count"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="like_count" label="参加活动人数">
        <uni-easyinput
          placeholder="参加活动人数"
          type="number"
          v-model="formData.like_count"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- <uni-forms-item name="location_ip" label="活动地点IP">
        <uni-easyinput placeholder="活动地点IP地址" v-model="formData.location_ip"></uni-easyinput>
      </uni-forms-item> -->
      <view class="uni-button-group">
        <button
          type="primary"
          class="uni-button"
          style="width: 100px"
          @click="submit"
          :disabled="isDisabled"
        >
          提交
        </button>
        <navigator open-type="navigateBack" style="margin-left: 15px">
          <button class="uni-button" style="width: 100px">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { validator } from "@/js_sdk/validator/news-articles-image.js";
import { store } from "@/uni_modules/uni-id-pages/common/store";

const db = uniCloud.database();
// const dbCmd = db.command;
const dbCollectionName = "news-articles-image";

function getValidator(fields) {
  let result = {};
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key];
    }
  }
  return result;
}

export default {
  data() {
    let formData = {
      user_id: "",
      category_id: "",
      avatar: "",
      content: "",
      article_status: 0,
      last_comment_user_id: "",
      publish_date: null,
      last_modify_date: null,
      title: "",
      coupon_id: "",
      start_time: null,
      end_time: null,
      provinces: null,
      region_address: null,
      location_name: "",
      view_count: null,
      like_count: null,
      location_ip: "",
    };
    return {
      provinces: [],
      valueAddress: ["", "", ""],
      formData,
      formDataId: "",
      originFormData: null,
      formOptions: {
        article_status_localdata: [
          {
            value: 0,
            text: "草稿箱",
          },
          {
            value: 1,
            text: "已发布",
          },
          {
            value: 2,
            text: "已过期",
          },
        ],
      },
      rules: {
        ...getValidator(Object.keys(formData)),
      },
    };
  },
  onLoad(e) {
    if (e.id) {
      const id = e.id;
      this.formDataId = id;
      // console.log('getDetail id: ', id);
      this.getDetail(id);
    }

    if (e.provinces) {
      const temp = decodeURIComponent(e.provinces);
      this.provinces = JSON.parse(temp);
      // console.log('getDetail provinces: ', this.provinces);
    }
  },
  onReady() {
    this.$refs.form.setRules(this.rules);
  },
  computed: {
    regionAddressText() {
      return this.formData.region_address?.text?.join("/") || "";
    },
    hasRegionAddressTest() {
      return this.formData.region_address?.text?.length > 0;
    },
    isSuperAdmin() {
      return this.$hasRole("admin");
    },
    userId() {
      if (store.hasLogin) {
        return store.userInfo._id;
      }
      uni.showModal({
        content: "获取用户信息失败，请重新登录",
        showCancel: false,
      });
      return "";
    },
    // 添加新的计算属性
    isDisabled() {
      return this.formData.article_status === 2 && !this.$hasRole("admin");
    },
  },
  methods: {
    setValueAddress() {
      if (!this.formData.region_address?.value || !this.provinces.length) {
        return ["", "", ""];
      }

      const [provinceCode, cityCode, districtCode] =
        this.formData.region_address.value;
      const valueAddress = [];

      // 查找省级索引
      const provinceIndex = this.provinces.findIndex(
        (p) => p.code === provinceCode
      );
      if (provinceIndex >= 0) {
        valueAddress[0] = provinceIndex;

        // 查找市级索引
        if (this.provinces[provinceIndex].children) {
          const cityIndex = this.provinces[provinceIndex].children.findIndex(
            (c) => c.code === cityCode
          );
          if (cityIndex >= 0) {
            valueAddress[1] = cityIndex;

            // 查找区级索引
            if (this.provinces[provinceIndex].children[cityIndex].children) {
              const districtIndex = this.provinces[provinceIndex].children[
                cityIndex
              ].children.findIndex((d) => d.code === districtCode);
              if (districtIndex >= 0) {
                valueAddress[2] = districtIndex;
              }
            }
          }
        }
      }

      this.valueAddress = [...valueAddress];
    },
    confirmRegionAddress(e) {
      console.log("confirmRegionAddress: ", e);
      this.formData.region_address = { ...e };
      console.log("this.valueAddress: ", this.valueAddress);
      // this.valueAddress = e.value;
    },
    goBack() {
      const eventChannel = this.getOpenerEventChannel();
      if (eventChannel && eventChannel.emit) {
        eventChannel.emit("refreshData");
      }
      setTimeout(() => uni.navigateBack(), 500);
    },

    /**
     * 验证表单并提交
     */
    submit() {
      uni.showLoading({
        mask: true,
      });
      this.$refs.form
        .validate()
        .then((res) => {
          return this.submitForm(res);
        })
        .catch(() => {})
        .finally(() => {
          uni.hideLoading();
        });
    },

    /**
     * 比较表单数据是否有变化
     * @param {Object} newData - 新的表单数据
     * @param {Object} oldData - 原始表单数据
     * @returns {Boolean} - 如果数据有变化返回true，否则返回false
     */
    compareData(newData, oldData) {
      const compareKeys = [
        "category_id",
        "title",
        "content",
        "article_status",
        "avatar",
        "publish_date",
        "last_modify_date",
        "start_time",
        "end_time",
        "region_address",
        "location_name",
      ];
      for (const key of compareKeys) {
        if (key === "avatar" || key === "content") {
          const newUrl = newData[key]?.url || newData[key] || "";
          const oldUrl = oldData[key]?.url || oldData[key] || "";
          if (newUrl !== oldUrl) return true;
        } else if (newData[key] !== oldData[key]) {
          return true;
        }
      }
      return false;
    },

    /**
     * 提交表单
     */
    submitForm(value) {
      const submitData = { ...value, user_id: this.userId };

      submitData.user_id = this.userId;

      if (submitData.avatar && submitData.avatar.url) {
        submitData.avatar = submitData.avatar.url;
      }
      if (submitData.content && submitData.content.url) {
        submitData.content = submitData.content.url;
      }

      // 比较数据是否有变化
      if (!this.compareData(submitData, this.originFormData)) {
        uni.showToast({
          title: "数据未发生变化",
          icon: "none",
        });
        return false;
      }

      // console.log('submitForm submitData: ', submitData);

      // 使用 clientDB 提交数据
      return db
        .collection(dbCollectionName)
        .doc(this.formDataId)
        .update(submitData)
        .then((res) => {
          uni.showToast({
            title: "修改成功",
          });
          this.getOpenerEventChannel().emit("refreshData");
          setTimeout(() => uni.navigateBack(), 500);
        })
        .catch((err) => {
          uni.showModal({
            content: err.message || "请求服务失败",
            showCancel: false,
          });
        });
    },

    /**
     * 获取表单数据
     * @param {Object} id
     */
    getDetail(id) {
      uni.showLoading({
        mask: true,
      });
      db.collection(dbCollectionName)
        .doc(id)
        .field(
          "user_id,category_id,avatar,content,article_status,last_comment_user_id,publish_date,last_modify_date,title,coupon_id,start_time,end_time,region_address,location_name,view_count,like_count,location_ip"
        )
        .get()
        .then((res) => {
          const data = res.result.data[0];
          if (data) {
            // 处理图片数据格式
            if (data.avatar) {
              data.avatar = { url: data.avatar };
            }
            if (data.content) {
              data.content = { url: data.content };
            }
            this.formData = { ...data };
            this.originFormData = { ...data };
            this.setValueAddress();
          }
        })
        .catch((err) => {
          uni.showModal({
            content: err.message || "请求服务失败",
            showCancel: false,
          });
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
    handleShowRegionAddress() {
      // console.log('region_address数据:', this.formData.region_address);
      console.log("valueAddress计算值:", this.valueAddress);

      this.$refs.pickerRegionAddress.show();
    },
    handleDeleteRegionAddress() {
      this.formData.region_address = null;
    },
  },
};
</script>
